//展开、合并 准备工作 默认合并 展开一个,其他同级的合并
/* $(".headline").on("click",function(){
	if($(this).find(".headline-status img").attr("src")=="img/add.png"){
		if($(this).parents(".collapse").prev(".headline").length>0){
			$(this).parent().siblings().children(".headline").find(".headline-status img").attr("src","img/add.png");
			$(this).parent().siblings().children(".headline").next(".collapse").collapse('hide');
		}else{
			$(".headline .headline-status img").attr("src","img/add.png");
			$(".headline").next(".collapse").collapse('hide');
		}
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".headline-status img").attr("src","img/minus.png");
	}else if($(this).find(".headline-status img").attr("src")=="img/minus.png"){
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".headline-status img").attr("src","img/add.png");
	}
}) */
//如果当前步骤没有打勾，默认打勾标志
$(".proceduralStep").each(function (){
	if ($(this).find("input").length < 1){
		var imgs = $(this).find("img");
		//var imgIndex = ok.find("img").length -2;
		var img = imgs[1];
		//console.log($(img))
		$(img).attr("class","headline-icon");
	}
})

/* 默认展开 展开一个,其他同级的不合并 */
$(".headline").each(function(){
	$(this).next(".collapse").collapse('show');
	$(this).find(".headline-status img").attr("src","img/minus.png");
})
$(".headline").on("click",function(){
	if($(this).next(".collapse").is(":hidden")){
		$(this).next(".collapse").css({"display":"block"})
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".headline-status img").attr("src","img/minus.png");
	}else{
		$(this).next(".collapse").css({"display":"none"})
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".headline-status img").attr("src","img/add.png");
	}
})

$(".stepheadline").each(function(){
	$(this).next(".collapse").collapse('show');
	$(this).find(".stepheadline-status img").attr("src","img/minus.png");
	// $(this).find(".step-open-close").text("收起");
})
$(".stepheadline").on("click",function(){
	if($(this).next(".collapse").is(":hidden")){
		$(this).next(".collapse").css({"display":"block"})
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".stepheadline-status img").attr("src","img/minus.png");
		// $(this).find(".step-open-close").text("收起");
	}else{
		$(this).next(".collapse").css({"display":"none"})
		$(this).next(".collapse").collapse('toggle');
		$(this).find(".stepheadline-status img").attr("src","img/add.png");
		// $(this).find(".step-open-close").text("展开");
	}
})




//点击完成步骤
$("li").each(function(){
	$(this).find(".para").css("display","inline");
	// 当 li 下还有其他的 ol/ul li 时，移除本身的input
	if ($(this).find("li").length>0){
		$(this).children(".liItem").remove()
	}
})

$(function(){
	// if($("#DmMedialist").children().length == 0){
	// 	$(".lbody").append('<button onclick="getAllStep()" style="float: right;" class="yesAnswer layui-btn layui-btn-normal">'+i18n("i18n-lan-Complete")+'</button>')
	// }else{
	// 	$(".lbody").append('<button onclick="getAllStep()" style="float: right;" class="yesAnswer layui-btn layui-btn-normal">'+i18n("i18n-lan-Complete")+'</button>')
	// }
})


$('input').on('click',function(){
	//当前的列表
	var ol = $(this).parent().parent();
	//当前列表所属的步骤
	var theStep = getProceduralStep(ol);
	if($(this).is(':checked')){
		//判断前一个大步骤是否完成
		var lastStep = theStep.prev();
		if(lastStep.attr("class") == "proceduralStep"){
			var lastStepImgs = lastStep.find("img");
			var lastStepImg = lastStepImgs[1];
			//$(lastStepImg).attr("class","headline-icon-my");
			if($(lastStepImg).attr("class")=="headline-icon-my"){
				layer.msg(i18n("i18n-alert-CompletePreBigStep"));
				return false;
			}
		}
		if(ol.prop('nodeName') == "OL"){
			//判断上一步骤是否完成
			if($(this).parent().prev().children("input").length>0){
				if($(this).parent().prev().children("input")[0].checked == false){
					layer.msg(i18n("i18n-alert-CompletePreStep"));
					return false;
				}
			}
		}
		getProceduralStepAllReady(theStep);
		parentStepIsReady(theStep);
		//步骤颜色标记
		$(this).parent().children(".para").css("color","#96d287");
	}else{
		if(ol.prop('nodeName') == "OL"){
			//还原完成标准
			var ok = theStep;
			if(ok.attr("class") == "proceduralStep"){
				var imgs = ok.find("img");
				//var imgIndex = ok.find("img").length -2;
				var img = imgs[1];
				$(img).attr("class","headline-icon-my")
			}
		}else if(ol.prop('nodeName')=="UL"){
			var inputs = ol.find("input")
			var index = inputs.length;
			var a = 0;
			for(i=0;i<index;i++){
				if(inputs[i].checked == true){
					a++;
				}
			}
			if(a < 1){
				//还原完成标准
				var ok = theStep;
				if(ok.attr("class") == "proceduralStep"){
					var imgs = ok.find("img");
					//var imgIndex = ok.find("img").length -2;
					var img = imgs[1];
					$(img).attr("class","headline-icon-my")
				}
			}
		}
		parentStepIsReady(theStep);
		//步骤颜色标记取消
		$(this).parent().children(".para").css("color","#ffffff");
	}

})

//获取步骤节点
function getProceduralStep(ol){
	if(ol.parent().attr("class") == "proceduralStep"){
		return ol.parent();
	}else{
		return getProceduralStep(ol.parent());
	}
}

//判断大步骤是否完成
function getProceduralStepAllReady(theStep){
	console.log(theStep);
	var ols = theStep.find("ol");
	console.log("ol:" + ols.length)
	var olOkTime = 0;

	var uls = theStep.find("ul");
	console.log("ul:" + uls.length)
	var ulOkTime = 0;

	for(var i = 0;i < ols.length; i++){
		var inputs= $(ols[i]).children("li").children("input");
		var index = inputs.length -1;
		if(inputs.length > 0){
			if(inputs[index].checked == true){
				olOkTime++;
			}
		}else{
			olOkTime++;
		}

	}
	for(var i = 0;i < uls.length; i++){
		var inputs = $(uls[i]).children("li").children("input");
		var index = inputs.length;
		if(inputs.length > 0){
			var a = 0;
			for(var j = 0 ; j < index; j++){
				if(inputs[j].checked == true){
					a++;
				}
			}
			if(a > 0){
				ulOkTime++;
			}
		}else{
			ulOkTime++;
		}

	}

	console.log("olOkTime:" + olOkTime);
	console.log("ulOkTime:" + ulOkTime);
	//说明当前大步骤已完成
	if(olOkTime == ols.length && ulOkTime == uls.length){

		if(theStep.attr("class") == "proceduralStep"){
			//console.log(ok.find(".headline-icon-my"))
			console.log("当前步骤完成了")
			var imgs = theStep.find("img");
			//var imgIndex = ok.find("img").length -2;
			var img = imgs[1];
			//console.log($(img))
			$(img).attr("class","headline-icon");
		}
	}else{
		if(theStep.attr("class") == "proceduralStep"){
			//console.log(ok.find(".headline-icon-my"))
			console.log("当前步骤没有完成")
			var imgs = theStep.find("img");
			//var imgIndex = ok.find("img").length -2;
			var img = imgs[1];
			//console.log($(img))
			$(img).attr("class","headline-icon-my");
		}
	}
}

//判断当前步骤的父步骤下的所有兄弟步骤是否都有完成标志
function parentStepIsReady(theStep){
	var parentStep = theStep.parent().parent().parent();
	var childrenReadyTimes = 0;
	if(parentStep.attr("class") == "proceduralStep" ){
		var childrenSteps = parentStep.find(".proceduralStep");
		for(var i = 0; i < childrenSteps.length; i++){
			var imgs = $(childrenSteps[i]).find("img");
			if(imgs.length > 0){
				var img = imgs[1];
				if($(img).attr("class") == "headline-icon"){
					childrenReadyTimes++;
				}
			}
		}

		if(childrenReadyTimes == childrenSteps.length){
			console.log("当前步骤的父步骤完成了")
			var imgs = parentStep.find("img");
			//var imgIndex = ok.find("img").length -2;
			var img = imgs[1];
			//console.log($(img))
			$(img).attr("class","headline-icon");
		}else{
			console.log("当前步骤的父步骤没有完成")
			var imgs = parentStep.find("img");
			//var imgIndex = ok.find("img").length -2;
			var img = imgs[1];
			//console.log($(img))
			$(img).attr("class","headline-icon-my");
		}
	}

}

//获取所有的步骤报文
function getAllStep(){
	var str ='';
	var inputs = $("input").length;
	for(i=0;i<inputs;i++){
		var input = $("input")[i];
		if($("input")[i].checked == true){
			var aa = $(input).parent().children(".para").text().replace(/\s+/g,"");
			str += aa + ";";
		}
	}
	window.parent.getStepReport(str);
}


// -------------------模拟仓储系统 begin ----------------

var dmcTitle = $(document).attr("title");
var STORAGE_IP = "http://127.0.0.1:8080/STORAGE/"

var dmc = "DMC-S1000DBIKE-AAA-D00-00-00-00AA-121A-A";

var stockarray = new Array();
var personarray = new Array();


// 物料查询
$(".btnStock").click(function () {
	var topMenus = getClass('td','partNumber');
	for(var i=0;i < topMenus.length; i++){
		console.log(topMenus[i].innerHTML);
		$.ajax({
			url:STORAGE_IP+"stock/get",
			method: "GET",
			dataType: "json",
			data:{
				"dmc":dmc,
				"material":topMenus[i].innerHTML
			},
			async: false,
			success:function (result) {
				console.log(result);
				$(".addbtnStock").css({"display":"inline-block","margin-left": "20px"});
				if(result.datas.records.length==0){
					$(topMenus[i]).parent().find(".stock").html("-");
					return;
				}
				$(topMenus[i]).parent().find(".stock").html(result.datas.records[0].stock);
				var stock = $(topMenus[i]).parent().find(".stock").html();
				var reqQuantity = $(topMenus[i]).parent().find(".reqQuantity").html();
				if (parseInt(stock) <parseInt(reqQuantity)){
					$(topMenus[i]).parent().find(".stock").css("color","red");
					var quantity = parseInt(reqQuantity)-parseInt(stock);

					var stockjson = {};

					stockjson.dmc=dmc;
					stockjson.name=$(topMenus[i]).innerHTML;
					stockjson.quantity=quantity;

					stockarray.push(stockjson);
				}
			},
			error: function () {
			}
		})
	}
})

$(".addbtnStock").click(function () {
	// 循环数组
	for(var i in stockarray){
		//layer.msg(JSON.stringify(stockarray[i]));
		var curr = stockarray[i];
		var records = getOrder(curr.dmc,curr.name);
		if (records.length>0){
			//更新
			curr.quantity = parseInt(curr.quantity)+parseInt(records[0].quantity);
			updateOrder(records[0].id,curr.dmc,dmcTitle,curr.name,curr.quantity);
		}else{
			//新增
			addOrder(curr.dmc,dmcTitle,curr.name,curr.quantity)
		}
	}
	layer.msg(i18n("i18n-alert-saveSuccess"))
})

// 可调配人员查询
$(".btnPerson").click(function () {
	var tradeMenus = getClass('td','trade');
	for(var i=0;i < tradeMenus.length; i++){
		console.log("第"+i+"个元素");
		var trade = tradeMenus[i].innerHTML;
		var skill = $(tradeMenus[i]).parent().find(".personSkill").html();
		$.ajax({
			url:STORAGE_IP+"person/get",
			method: "GET",
			dataType: "json",
			data:{
				"dmc":dmc,
				"trade":trade,
				"skill":skill
			},
			async: false,
			success:function (result) {
				console.log(result);
				$(".addbtnPerson").css({"display":"inline-block","margin-left": "20px"});
				if(result.datas.records.length==0){
					$(tradeMenus[i]).parent().find(".personNum").html("-");
					return;
				}
				$(tradeMenus[i]).parent().find(".personNum").html(result.datas.records[0].numRequired);
				var hasNum = $(tradeMenus[i]).parent().find(".personNum").html();
				var requiredNum = $(tradeMenus[i]).parent().find(".numRequired").html();
				if (parseInt(hasNum) <parseInt(requiredNum)){
					$(tradeMenus[i]).parent().find(".personNum").css("color","red");

					var num = parseInt(requiredNum)-parseInt(hasNum);

					var personjson = {};

					personjson.dmc=dmc;
					personjson.trade=trade;
					personjson.skill=skill;
					personjson.num=num;

					personarray.push(personjson);
				}
			},
			error: function () {
			}
		})
	}
})

$(".addbtnPerson").click(function () {
	// 循环数组
	for(var i in personarray){
		var curr = personarray[i];
		var records = getOrderPerson(curr.dmc,curr.trade,curr.skill);
		if (records.length>0){
			//更新
			//layer.msg("更新")
			curr.num = parseInt(curr.num)+parseInt(records[0].num);
			updateOrderPerson(records[0].id,curr.dmc,dmcTitle,curr.trade,curr.skill,curr.num);
		}else{
			//新增
			//layer.msg("新增")
			addOrderPerson(curr.dmc,dmcTitle,curr.trade,curr.skill,curr.num)
		}
	}
	layer.msg(i18n("i18n-alert-saveSuccess"));
})

// 添加缺货订单
function addOrder(dmc,dmcTitle,name,quantity) {
	$.ajax({
		type: "post",
		url:STORAGE_IP+"order/add",
		dataType:"json",
		async: false,
		contentType: 'application/json;charset=UTF-8',
		cache:false,
		data:JSON.stringify(
			{
				"dmc":dmc,
				"dmcTitle":dmcTitle,
				"name":name,
				"quantity":quantity,
			}
		),
		beforeSend: function() {
			// layer.load(1);
		},
		error: function() {
			// layer.closeAll('loading');
			// layer.layer.msg("与服务器连接失败!");
		},
		success: function(res) {
			console.log(res)
			if (res.resp_code==0){
				layer.msg(i18n("i18n-alert-saveOrderSuccess"))
			}
		}
	});
}

// 更新缺货订单
function updateOrder(id,dmc,dmcTitle,name,quantity) {
	$.ajax({
		type: "post",
		url:STORAGE_IP+"order/update",
		dataType:"json",
		contentType: 'application/json;charset=UTF-8',
		cache:false,
		async: false,
		data:JSON.stringify(
			{
				"id":id,
				"dmc":dmc,
				"dmcTitle":dmcTitle,
				"name":name,
				"quantity":quantity,
			}
		),
		beforeSend: function() {
			// layer.load(1);
		},
		error: function() {
			// layer.closeAll('loading');
			// layer.layer.msg("与服务器连接失败!");
		},
		success: function(res) {
			console.log(res)
			if (res.resp_code==0){
				//layer.msg("新增补货订单成功!")
			}
		}
	});
}

// 获取数据模块缺货订单 信息
function getOrder(dmc,name) {
	 var records ;
	 $.ajax({
		type: "get",
		url:STORAGE_IP+"order/get",
		 async:false,
		cache:false,
		data: {
				"dmc":dmc,
				"name":name
			}
		,
		beforeSend: function() {
			// layer.load(1);
		},
		error: function() {
			// layer.closeAll('loading');
			// layer.layer.msg("与服务器连接失败!");
		},
		success: function(res) {
			console.log(res)
			records =  res.datas.records;
		}
	});
	 return records;
}


// 添加缺少人员
function addOrderPerson(dmc,dmcTitle,trade,skill,num) {
	$.ajax({
		type: "post",
		url:STORAGE_IP+"orderPerson/add",
		dataType:"json",
		async: false,
		contentType: 'application/json;charset=UTF-8',
		cache:false,
		data:JSON.stringify(
			{
				"dmc":dmc,
				"dmcTitle":dmcTitle,
				"trade":trade,
				"skill":skill,
				"num":num,
			}
		),
		success: function(res) {
			console.log(res)
			if (res.resp_code==0){
				console.log("新增缺少人员信息成功!")
			}
		}
	});
}

// 更新缺少人员信息
function updateOrderPerson(id,dmc,dmcTitle,trade,skill,num) {
	$.ajax({
		type: "post",
		url:STORAGE_IP+"orderPerson/update",
		dataType:"json",
		contentType: 'application/json;charset=UTF-8',
		cache:false,
		async: false,
		data:JSON.stringify(
			{
				"id":id,
				"dmc":dmc,
				"dmcTitle":dmcTitle,
				"trade":trade,
				"skill":skill,
				"num":num,
			}
		),
		success: function(res) {
			console.log(res)
			if (res.resp_code==0){
				console.log("更新成功")
			}
		}
	});
}

// 获取数据模块缺少人员信息
function getOrderPerson(dmc,trade,skill) {
	var records ;
	$.ajax({
		type: "get",
		url:STORAGE_IP+"orderPerson/get",
		async:false,
		cache:false,
		data: {
			"dmc":dmc,
			"trade":trade,
			"skill":skill
		},
		success: function(res) {
			console.log(res)
			records =  res.datas.records;
		}
	});
	return records;
}





// 获得标签名为tagName,类名className的元素
function getClass(tagName,className){
	//支持这个函数
	if(document.getElementsByClassName){
		return document.getElementsByClassName(className);
	}else{
		var tags=document.getElementsByTagName(tagName);//获取标签
		var tagArr=[];//用于返回类名为className的元素
		for(var i=0;i < tags.length; i++)
		{
			if(tags[i].class == className)
			{
				tagArr[tagArr.length] = tags[i];//保存满足条件的元素
			}
		}
		return tagArr;
	}

}


// $('input').hover(
// 	function(){
// 		$(this).parent().children(".para").css("color","#96d287");
// 	},function(){
// 		if(!$(this).is(':checked')){
// 			$(this).parent().children(".para").css("color","#ffffff");
// 		}
// 	}
// )
$("body").on("mouseenter", "input[type='checkbox']", function() {
	$(this).parent().children(".para").css("color","#96d287");
});
$("body").on("mouseleave", "input[type='checkbox']", function() {
	if(!$(this).is(':checked')){
		$(this).parent().children(".para").css("color","#ffffff");
	}
});
